<template>
  <div>
    <el-row>
      <el-col style="margin-top: 10px">
        <el-input
          v-model="search"
          style="width: 240px"
          placeholder="请输入药盒名"
        />
        <el-button style="margin-left: 20px" type="primary">搜索</el-button>
        <!-- <el-button style="margin-left: 20px" type="primary" @click="add"
          >添加药盒</el-button
        > -->
      </el-col>
      <el-col style="margin-top: 10px">
        <el-table
          class="box-table"
          :data="Data"
          :stripe="true"
          :border="true"
          :fit="true"
        >
          <el-table-column
            prop="name"
            label="药盒名"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="SnNo"
            label="设备号"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="username"
            label="使用者"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="auto"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="
                  info(scope.row);
                  dialogVisible = true;
                "
                >配药</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="
                  info2(scope.row);
                  dialogVisible2 = true;
                "
                >药盒状态</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col style="margin: 0 auto">
        <el-card>
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :total="Total"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <!-- 配药 -->
      <el-dialog
        v-model="dialogVisible"
        title="选择药盒用药方案"
        width="50%"
        :before-close="handleClose"
      >
        <el-form :model="form" label-position="right">
          <el-form-item label="药盒方案:" label-width="150px">
            <el-select
              style="width: 180px"
              v-model="form.devicemrid"
              placeholder="请选择药盒方案"
              @change="change_fangan"
            >
              <el-option
                v-for="option in yaocang_options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="服药日期:" label-width="150px">
          
          </el-form-item> -->
        </el-form>

        <el-table
          class="box-table"
          :data="msg_info"
          :stripe="true"
          :border="true"
          :fit="true"
          style="margin-top: 20px"
        >
          <el-table-column
            prop="WarehouseNumber"
            label="药仓"
            width="auto"
            align="center"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="Time"
            label="服药日期"
            width="auto"
            align="center"
            header-align="center"
          >
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.Time"
                type="date"
                placeholder="选择服药日期"
              />
            </template>
          </el-table-column>
        </el-table>
        <el-button link type="primary" size="small" @click="baocun_peiyao()"
          >保存</el-button
        >
      </el-dialog>

      <!-- 药盒状态 -->
      <el-dialog
        v-model="dialogVisible2"
        title="药盒状态"
        width="50%"
        :before-close="handleClose"
      >
        <el-descriptions>
          <el-descriptions-item label="药盒名:">{{
            zhuangtai_form.name
          }}</el-descriptions-item>
          <el-descriptions-item label="电量:">{{
            zhuangtai_form.electricity
          }}</el-descriptions-item>
          <el-descriptions-item label="信号强度:">{{
            zhuangtai_form.rssi
          }}</el-descriptions-item>
          <el-descriptions-item label="位置:">
            <el-tag size="small">{{ zhuangtai_form.location }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="药盒方案:">{{
            zhuangtai_form.fangan
          }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import apiService from "@/services/apiService";
import { conversionUtcDate, base64ToExcelAndDownload } from "@/utils/auth";
import { v4 as uuidv4 } from "uuid";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { message } from "@/utils/message";

//表格数据
const Data = ref<any>([
]);
const currentPage = ref(1); // 当前页数
const pageSize = ref(10); // 每页条数
const Total = ref<number>(1); //总条数
const search = ref("");
//获取药盒数据列表
const GetList = () => {
  const params = {
    msgid: "PagingFindMedicineBox",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: currentPage.value,
      pagesize: pageSize.value,
      userid: null
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log(res.data);
      Data.value = [];
      Data.value.push(...res.data.body.devices);
      Total.value = res.data.body.total;
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
// 监听页码变化
const handleCurrentChange = val => {
  currentPage.value = val;
  GetList();
};

// 监听每页条数变化
const handleSizeChange = val => {
  pageSize.value = val;
};

//配药
const msg_info = ref<any>([]);
const info = row => {
  medicineboxid.value = row.id;
};
const dialogVisible = ref(false);
const form = ref<any>({
  devicemrid: ""
});
//药盒方案列表
const yaocang_options = ref<any>([]);
const medicineboxid = ref<any>("");
const Yaohe_Arr = () => {
  const params = {
    msgid: "PagingFindDeviceMR",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      pageno: 1,
      pagesize: 1000,
      userid: null
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log("获取当前药盒方案:", res.data);
      yaocang_options.value = [];
      res.data.body.devicemrs.forEach(item => {
        yaocang_options.value.push({
          value: item.id,
          label: item.name
        });
      });
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
//改变方案
const change_fangan = () => {
  msg_info.value = [];
  console.log("当前方案:", form.value.devicemrid);
  const params = {
    msgid: "FindDeviceMRByID",
    token: getToken().accessToken,
    seq: uuidv4(),
    body: {
      id: form.value.devicemrid
    }
  };

  apiService
    .post("", params)
    .then((res: any) => {
      // 使用 any 类型断言
      console.log("当前药盒方案详情:", res.data);
      res.data.body.drugWarehousemrs.forEach(item => {
        msg_info.value.push({
          WarehouseNumber: item.serialno,
          Time: ""
        });
      });
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
};
//保存方案
const baocun_peiyao = () => {
  if (
    medicineboxid.value != "" &&
    form.value.devicemrid != "" &&
    msg_info.value != []
  ) {
    let arr = [];
    msg_info.value.forEach(item => {
      if (item.Time == "") {
        arr.push(item.WarehouseNumber);
      }
    });
    const result = arr.join(",");
    console.log("当前未设置服药日期的药仓:", arr);
    if (arr.length == 0) {
      const params = {
        msgid: "StartDrug",
        token: getToken().accessToken,
        seq: uuidv4(),
        body: {
          medicineboxid: medicineboxid.value,
          devicemrid: form.value.devicemrid,
          warehouses: msg_info.value
        }
      };

      apiService
        .post("", params)
        .then((res: any) => {
          // 使用 any 类型断言
          console.log("保存方案:", res.data);
          if (res.data.code == 200) {
            dialogVisible.value = false;
            message("保存成功", { type: "success" });
            form.value = [];
            msg_info.value = [];
            GetList();
          }
        })
        .catch(error => {
          console.error("Error fetching data:", error);
        });
    } else {
      message(`当前${result}药盒未设置用药日期`, { type: "error" });
    }
  } else {
    message("请填写完整信息", { type: "error" });
  }
};

//药盒状态
const dialogVisible2 = ref(false);
const zhuangtai_form = reactive({
  name: "测试药盒",
  electricity: "100", //电量
  rssi: "100", //信号
  location: "浙江省杭州市钱塘区金沙印象城", //位置
  fangan: "测试药盒方案1" //药盒方案
});
const info2 = row => {
  zhuangtai_form.name = row.name;
  zhuangtai_form.electricity = row.electricity;
  zhuangtai_form.rssi = row.rssi;
  zhuangtai_form.location = row.location;
  zhuangtai_form.fangan = row.devicemrname;
};

const handleClose = (done: () => void) => {
  done();
  form.value = [];
  msg_info.value = [];
};

onMounted(() => {
  GetList();
  Yaohe_Arr();
});
</script>

<style lang="scss" scoped></style>
